﻿using ASmile.Extend;
using ASmile.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace ASmile.ExtService
{
    public static class ServiceHelper
    {
        public static List<IServiceCore> ServiceList { get; } = new List<IServiceCore>();

        public static void Run(string cfgFile)
        {
            var rootPath = AppDomain.CurrentDomain.BaseDirectory;
            var fileFullName = Path.Combine(rootPath, cfgFile);
            using (StreamReader sr = new StreamReader(fileFullName))
            {
                string row;
                while (!sr.EndOfStream)
                {
                    row = sr.ReadLine().Trim();
                    if (row.IsEmpty() || row.StartsWith("#")) continue;
                    var cols = row.SplitByNotEmpty(",");

                    var ser = ReflectionHelper.CreateInstance(cols[0], cols[1]) as IServiceCore;
                    if (ser == null) return;
                    ServiceList.Add(ser);
                }
            }

            foreach (var item in ServiceList)
            {
                Task.Factory.StartNew(item.Run);
            }
        }

        public static void Run()
        {
            Run("ASmile.ExtService");
        }

    }
}
